﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using AutoUpdate.BLL;
using AutoUpdate.Models;
// using AutoUpdate.BLL;
using Newtonsoft.Json;

namespace AutoUpdate.Controllers
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class T_SysUpdateController : ControllerBase
    {
        T_SysUpdateManager manager = new T_SysUpdateManager();
        public string Get()
        {
            string result = "";
            result = JsonConvert.SerializeObject(manager.GetModels(p=>true));
            return result;
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("{id}")]
        public FileResult GetFile(string id)
        {
            List<TSysUpdate> list = manager.GetModels(t => t.Id.ToString() == id).ToList();
            if (list.Count > 0)
            {
                byte[] file = list[0].Exefile;
                MemoryStream ms = new MemoryStream(file);
                ms.Position = 0;
                return File(ms, "application/octet-stream", list[0].Fmemo);

            }

            return null;

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="update"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromForm]TSysUpdate update, IFormFile file)
        {
            if (ModelState.IsValid)
            {
                List<TSysUpdate> tSysUpdate = manager.GetModelsByPage(1, 1, false, p => p.FdownNum, p => true).ToList();
                if (tSysUpdate != null)
                {
                    int num = tSysUpdate[0].FdownNum == null ? 0 : Convert.ToInt32(tSysUpdate[0].FdownNum);
                    update.FdownNum = num + 1;
                }
                var stream = new MemoryStream();
                await file.CopyToAsync(stream);
                update.Exefile = stream.ToArray();
                manager.Add(update);
                return Content("成功"); 
            }

            return null;
        }

        [HttpPost]
        public string GetUpdate([FromForm]string fid, string modifyTime,string FProductID)
        {
            string result = "";
            
            return result;
        }

        

    }
}
